package com.njlime.sys.web;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.exception.WebException;
import com.njlime.sys.security.util.UserUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常集中处理类
 * @author Dean
 *
 */
public class ExceptionHandler implements HandlerExceptionResolver {
    Logger logger = Logger.getLogger(ExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		ex.printStackTrace();
		ModelAndView mv = new ModelAndView();
        String requestUri = request.getRequestURI();
        if(requestUri.contains("/app/")){
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                FastJsonJsonView view = new FastJsonJsonView();
                Map<String, Object> attributes = new HashMap<String, Object>();
                if(ex instanceof WebException){
                    attributes.put("resCode", ((WebException) ex).getExceptionCode());
                    attributes.put("message", ex.getMessage());
                }else{
                    attributes.put("resCode", ExceptionState.UNKNOWN_EXCEPTION);
                    attributes.put("message", "服务器繁忙，请联系管理员");
                }
                view.setAttributesMap(attributes);
                mv.setView(view);
            }else{
                mv.setViewName("/app/index");
                mv.addObject("pv","subscribe");
                String msg = "";
                try {
                    if (ex instanceof WebException) {
                        msg = new String(Base64.encodeBase64(ex.getMessage().getBytes("utf8")));
                    } else {
                        msg = new String(Base64.encodeBase64("服务器繁忙，请联系管理员".getBytes("utf8")));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                mv.addObject("msg", msg);
            }
        }else{
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            /*  使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常   */
                FastJsonJsonView view = new FastJsonJsonView();
                Map<String, Object> attributes = new HashMap<String, Object>();
                if(ex instanceof WebException){
                    attributes.put("resCode", ((WebException) ex).getExceptionCode());
                    attributes.put("message", ex.getMessage());
                }else{
                    attributes.put("resCode", ExceptionState.UNKNOWN_EXCEPTION);
                    attributes.put("message", "用户授权异常，请联系管理员");
                }
                view.setAttributesMap(attributes);
                mv.setView(view);
            }else{
                mv.setViewName("/exception");
                if(ex instanceof WebException){
                    mv.addObject("resCode", ((WebException) ex).getExceptionCode());
                    mv.addObject("message", ex.getMessage());
                }else{
                    mv.addObject("resCode", ExceptionState.UNKNOWN_EXCEPTION);
                    mv.addObject("message", "用户授权异常，请联系管理员");
                }
                mv.addObject("name", UserUtils.getUser().getName());
                mv.addObject("head_url", UserUtils.getUser().getHead_url());
            }
        }
		return mv;
	}

}
